import React, {Component} from 'react';
import Taro from '@tarojs/taro';
import {Block, Image, Text, View} from '@tarojs/components'
import {AtIcon, AtInput, AtButton} from 'taro-ui'
import {
  COUPON_DETAIL,
  COUPON_POSTER,
  COUPON_RECEIVE,
  COUPON_EXCHANGE,
  TARO_ENV, RESOURCE_URL
} from "../../constants/api";
import {user} from "../../utils/user.service";
import {newHttp} from "../../utils/request";
import {vcmonitor} from "../../utils/tools";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {h5Wx} from "../../utils/h5.service";
import './detail.scss'

export default class Detail extends Component {
  state: {
    couponExtensionUserId: any
    couponExtensionType: any
    shareImg: string
    listInfo: object | false
    showLoading: boolean
    show: boolean
    type: 0 | 1
    exchangeCode: string
    exchangeCodeShow: boolean
    exchangeInfo: any
  } = {
    couponExtensionUserId: '',
    couponExtensionType: '',
    shareImg: '',
    listInfo: false,
    showLoading: true,
    show: false,
    type: 0,
    exchangeCode: '',
    exchangeCodeShow: false,
    exchangeInfo: []
  }

  async UNSAFE_componentWillMount() {
    const uuid = this.params.uuid || ''
    const type = this.params.type || 0
    const couponExtensionUserId = this.params.couponExtensionUserId || ''
    const couponExtensionType = this.params.couponExtensionType || ''
    const listInfo = await this.getData(uuid)
    this.shareParams = await user.getSellerParams()
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
      //如果允许分享
      if (listInfo.share_type && listInfo.share_type === 1) {
        const shareData = {
          title: '我抢到优惠券啦！召唤小伙伴一起来抢，名额有限，快来抢！',
          desc: '世界一直在变，扫货的心不变。任性购物，说买就买。',
          link: window.location.origin + '/main/coupon/detail?' + this.shareParams + '&uuid=' + listInfo.uuid,
          imgUrl: RESOURCE_URL + '/resources/images/coupon_logo.png'
        }
        h5Wx.share(shareData)
      }
    }
    this.setState({listInfo, type, showLoading: false, couponExtensionUserId, couponExtensionType})
  }

  async componentDidShow() {
    vcmonitor(this)
    const {showLoading} = this.state
    if (!showLoading) {
      const uuid = this.params.uuid || 0
      const listInfo = await this.getData(uuid)
      this.setState({listInfo})
    }
  }

  shareParams
  params = Taro.getCurrentInstance().router.params

  async getData(coupon_uuid) {
    const is_use = this.params.type || 0
    const listInfo = await newHttp.catchPost(COUPON_DETAIL, {coupon_uuid, is_use})
    return listInfo || false
  }

  async saveImg() {
    const {shareImg} = this.state
    Taro.showLoading({title: '下载中...'})
    Taro.getImageInfo({
      src: shareImg,
    }).then((res) => {
      Taro.hideLoading()
      Taro.saveImageToPhotosAlbum({
        filePath: res.path,
      }).then(() => {
        Taro.showToast({
          title: '保存成功，请进入相册查看',
          icon: 'none'
        })
      })
    }).catch(err => {
      console.log(err)
      Taro.hideLoading()
      Taro.showToast({title: '海报不存在', icon: 'none'})
    })
    this.closeWow()
  }

  async closeWow() {
    const {show, listInfo} = this.state
    Taro.showLoading({title: '加载中...'})
    let shareImg = await newHttp.catchPost(COUPON_POSTER + listInfo.DT_RowId, {})
    if (shareImg) {
      shareImg = shareImg.url
    }
    Taro.hideLoading()
    this.setState({
      shareImg,
      show: !show
    })
  }

  // 优惠券兑换
  async couponExchange(coupon_id, e) {
    e.stopPropagation()
    const {listInfo, exchangeCode, couponExtensionUserId, couponExtensionType} = this.state
    const that = this
    const ret = await newHttp.post(COUPON_EXCHANGE, {
      coupon_id,
      code: exchangeCode,
      couponExtensionUserId,
      couponExtensionType
    }, true)
    if (ret.data) {
      listInfo.is_can_receive = ret.data.data
      Taro.showToast({
        title: '领取成功',
        icon: 'none',
        mask: true
      })
      setTimeout(() => {
        that.setState({listInfo}, () => {
          let mpkey = ''
          const uInfo = Taro.getStorageSync('user') || ''
          if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
            mpkey = uInfo.mpkey
          }
          Taro.redirectTo({url: '/main/coupon/index' + '?mpkey=' + mpkey})
        })
      }, 1500)
    } else {
      Taro.showToast({
        title: ret.message || '领取失败',
        icon: 'none',
        mask: true
      })
      that.setState({exchangeInfo: ret})
    }
  }

  // 优惠券领取
  async receive(coupon_uuid, e) {
    e.stopPropagation()
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        user.jumpLogin()
      }, 1500)
      return
    }
    const {listInfo, couponExtensionUserId, couponExtensionType} = this.state
    const that = this
    if (listInfo.exchange_type == 1) {
      this.setState({exchangeCodeShow: true})
    } else {
      const ret = await newHttp.post(COUPON_RECEIVE, {coupon_uuid, couponExtensionUserId, couponExtensionType}, true)
      if (ret.data != undefined) {
        listInfo.is_can_receive = ret.data.isCanReceiveCoupon
        Taro.showToast({
          title: '领取成功',
          icon: 'none',
          mask: true
        })
        that.setState({listInfo})
        setTimeout(() => {
          if (ret.data.isUseId) {
            Taro.navigateTo({
              url: '/main/coupon/coupon-goods?id=' + ret.data.isUseId
            })
          }
        }, 2500)
      } else if (ret.message === '没领到哦 此优惠券已领取完') {
        Taro.showToast({
          title: ret.message,
          icon: 'none',
          mask: true,
          duration: 2500
        })
        this.componentDidShow()
        that.setState({exchangeInfo: ret})
      } else {
        Taro.showToast({
          title: ret.message || '领取失败',
          icon: 'none',
          mask: true
        })
        that.setState({exchangeInfo: ret})
      }
    }
  }

  goUse(listInfo, e) {
    e.stopPropagation()
    const url = listInfo.url || '/main/coupon/coupon-goods?id=' + listInfo.id
    Taro.navigateTo({
      url
    })
  }

  handleChange(value) {
    this.setState({
      exchangeCode: value
    })
    // 在小程序中，如果想改变 value 的值，需要 `return value` 从而改变输入框的当前值
    return value
  }

  render() {
    const {show, shareImg, listInfo, type, exchangeCodeShow, exchangeInfo} = this.state
    return (
      <View className='coupon-detail-root'>
        <GzhAuth />
        {listInfo && <Block>
          {show && <View className='coupon-wow'>
            <View className='coupon-wow-bj' onClick={this.closeWow.bind(this)} />
            <Image className='coupon-wow-img' src={shareImg} />
            {TARO_ENV == 'h5' ?
              <View className='coupon-wow-save-h5' onClick={this.saveImg.bind(this)}>长按图片保存到相册</View> :
              <View className='coupon-wow-save' onClick={this.saveImg.bind(this)}>保存到相册</View>}
          </View>}
          <View className='top-info'>
            <View className='top-info-mj'>{listInfo.name}</View>
            <View className='top-info-e'>￥<Text>{listInfo.discounts_money}</Text></View>
            <View
              className='top-info-xz'
            >{listInfo.can_use_limit_money ? `满${listInfo.can_use_limit_money}可用` : '无门槛'}</View>
            {!!type && !!listInfo.isCanToUse &&
              <View className='top-info-lq' onClick={this.goUse.bind(this, listInfo)}>去使用</View>}

            {listInfo.is_can_receive === 0 && <View className='top-info-lq'
              onClick={this.receive.bind(this, listInfo.uuid)}
            >{listInfo.exchange_type == 1 ? '立即兑换' : '立即领取'}</View>}
            {/*{listInfo.is_can_receive === 1 && <Image className={'top-info-lq-p'} src={`${RESOURCE_URL}/resources/images/couponIcon-white.png`}/>}*/}
            {listInfo.is_can_receive === 2 && <Image className='top-info-lq-p'
              src='https://resource.ivcheng.com/upload/images/20210525/1621945212040_603.png'
            />}
            {!!listInfo.share_type && process.env.TARO_ENV !== 'tt' &&
              <View className='top-info-share' onClick={this.closeWow.bind(this)}>
                <AtIcon prefixClass='xxhz' value='fenxiang' size='28' color='#fff' />
              </View>}
          </View>
          <View className='more-info'>
            <View className='more-info-item'>
              <View className='more-info-title'>{listInfo.exchange_type == 1 ? '兑换有效期' : '有效期'}</View>
              <View className='more-info-desc'>{listInfo.date_show}</View>
            </View>
            <View className='more-info-item'>
              <View className='more-info-title'>使用规则</View>
              <View className='more-info-desc'>{listInfo.full_str}</View>
            </View>
            <View className='more-info-item'>
              <View className='more-info-title'>使用说明</View>
              <View className='more-info-desc'>
                <text>{listInfo.can_get_num_limit_type_str}</text>
              </View>
            </View>
          </View>
        </Block>}
        {exchangeCodeShow && <View className='curtainRoot'>
          <View className='exchangeCode-root'>
            <View className='title'>兑换码</View>
            <View className='tips' />
            <View className='item item-one'>
              <AtInput
                name='exchangeCode'
                type='number'
                placeholder='请填写你的兑换码'
                value={this.state.exchangeCode}
                onChange={this.handleChange.bind(this)}
              />
            </View>
            {!!exchangeInfo.message ?
              <View className='tips'>请确认您的兑换码是否正确或未使用过</View>
              :
              <View className='tips' />
            }
            <View className='item button2'>
              <AtButton onClick={this.couponExchange.bind(this, listInfo.DT_RowId)}>确定兑换</AtButton>
            </View>
            <View onClick={() => {
              this.setState({exchangeCodeShow: false})
            }} className='close'
            ><AtIcon prefixClass='car' value='iconguanbi' color='#D8D8D8' />
            </View>
          </View>
        </View>}
      </View>
    )
  }
}
